package com.changgou.goods.controller;
import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.goods.exception.CustomException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 统一异常处理类
 */
@ControllerAdvice
public class BaseExceptionHandler {

    @ExceptionHandler(value = CustomException.class)
    @ResponseBody
    public Result customException(CustomException e){
        //打印到控制台
        e.printStackTrace();
        //往日志中添加数据
        System.out.println(e.getClz().getName());
        //发送短信
        String message = e.getMessage();
        switch (message){
            case "商品不存在":
                e.setCode(StatusCode.NOT_EXIST);
                break;
            case "商品未被删除":
                e.setCode(StatusCode.UNDELETE);
                break;
            case "商品审核未通过":
                e.setCode(StatusCode.UNACCESS);
                break;
            default:
                e.setCode(StatusCode.ERROR);
                break;
        }
        return new Result(false, e.getCode(), e.getMessage());
    }

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result error(Exception e){
        e.printStackTrace();
        return new Result(false, StatusCode.ERROR, e.getMessage());
    }
}
